<template>
	<div class="organ-manage-container">
		<filterBar ref="filterBar" :workshopList="workshopList"
		:productionLineList="productionLineList"
		:procedureList="procedureList"
		:materialList="materialList"
		@on-search="refresh"
		@downloadSprintTestReport="downloadSprintTestReport"
		@exportExcel="exportExcel"
		@on-changeCarRoom="changeCarRoom"
		@on-changeProdutionLine="changeProdutionLine"
		@on-resetSearch="ResetSearch"></filterBar>
		<div ref="sprintReport">
			<div class="productionScheduling-main" v-show="!tableShow">
				<div class="pm-word">点击<a @click='refresh'>自动排程</a>按钮后，即可显示数据</div>
			</div>
			<w-table
				ref="listTable"
				:tableColumn="tableColumn"
				:listData="tableData"
				:showColumnFilterBtn="false"
				:showTools="true"
				:showToolsLeft="false"
				:selectable="false"
				:showPagination="false"
				v-show="tableShow"
				:minHeight="`${(tableData.length + 2) * 45}px`"
			>
				<div slot="btn-tools-right" class="tools-right">
					<el-tag
						v-for="(item, index) in headProduceList"
						:color="item === 'red' ? 'red' : produceColor[index]"
						:key="index"
						:style="{width:(item === 'red' ? '50px' : 'auto')}"
						effect="dark" style="border: none;margin-left: 10px;">
						{{ item === 'red' ? '' : item }}
					</el-tag>
				</div>
			</w-table>
		</div>
		<w-table
			ref="mergelistTable"
			id="table-content"
			style="margin-top: 20px;"
			:tableColumn="mergetableColumn"
			:listData="mergeTableData"
			:showColumnFilterBtn="false"
			:showTools="false"
			:selectable="false"
			:showPagination="false"
			v-show="mergetableShow"
			:minHeight="`${(mergeTableData.length + 2) * 45}px`"
		>
		</w-table>
	</div>
</template>
<script>
// 工序颜色
import filterBar from './FilterBar.vue'
import axios from 'axios'
export default {
	name: 'listContainer',
	components: {
		filterBar
	},
	data () {
		return {
			tableColumn: [],
			headProduceList: [],
			tableData: [],
			workshopList: [],
			workshopListCache: [],
			productionLineList: [],
			productionLineListCache: [],
			procedureList: [],
			materialList: [],
			produceColor: [
				'#409EFF', '#67C23A', '#E6A23C', '#E0D61A', '#1AE0B8',
				'#911AE0', '#E01AA8', '#761AE0', '#E01AA1', '#E0A11A',
				'#00FF7F', '#C0FF3E', '#FFF68F', '#20B2AA', '#EEE8AA',
				'#8B658B', '#FFC1C1', '#FF8247', '#FF7F24', '#FF00FF',
				'#BA55D3', '#FFA500', '#8B4500', '#FF4500', '#FF1493',
				'#FFF0F5', '#F0FFFF', '#836FFF', '#4876FF', '#8B4789',
				'#36648B', '#68228B', '#551A8B', '#B0E2FF', '#8B7B8B',
				'#FF4500', '#FF7F50', '#FFA07A', '#A52A2A', '#FFD39B',
				'#FFD700', '#228B22', '#BC8F8F', '#A0522D', '#F5DEB3',
				'#DB7093', '#EE82EE', '#BA55D3', '#A020F0', '#9370DB'
			],
			tableShow: false,
			mergetableShow: false,
			mergetableColumn: [],
			mergeTableData: []
		}
	},
	created () {
		this.findScreeningList()
		this.findProcedureListByProcedureLineId()
		this.findMaterialList()
	},
	methods: {
		refresh () {
			// this.$refs.listTable.clearSelected()
			// this.findScreeningList()
			// this.findProcedureListByProcedureLineId('')
			return this.productionPlanQuery()
		},
		getSearchParams () {
			const params = {
				...this.$refs.filterBar.getFilterParams()
			}
			return {
				...params
			}
		},
		findScreeningList () {
			return this.$fxApi('schedule.findScreeningList').then(res => {
				this.workshopList = res.carRoomEntities || []
				this.productionLineList = res.productionLineEntiries || []
				this.workshopListCache = res.carRoomEntities || []
				this.productionLineListCache = res.productionLineEntiries || []
				return Promise.resolve(res)
			})
		},
		findProcedureListByProcedureLineId (carRoomId, productionLineId) {
			return this.$fxApi('schedule.findProcedureListByProcedureLineId')({
				query: {
					carRoomId: carRoomId,
					productionLineId: productionLineId
				}
			}).then(res => {
				this.procedureList = res || []
				return Promise.resolve(res)
			})
		},
		findMaterialList () {
			return this.$fxApi('material.findListAll').then(res => {
				this.materialList = res.filter(p => {
					return p.processingFlag !== 2
				}) || []
				return Promise.resolve(res)
			})
		},
		productionPlanQuery (searchParams) {
			this.mergetableColumn = []
			this.tableColumn = []
			return this.$fxApi('schedule.AutoScheduleToCreateStationTask')({ data: this.getSearchParams() }).then(res => {
				this.headProduceList = res.headList
				if (this.headProduceList) {
					this.headProduceList.push('red')
				}
				if (res.topDataList) {
					res.topDataList.forEach(topData => {
						const redUnit = []
						topData.msg.forEach(msg => {
							const allRed = msg.timeUnit.every(t => {
								return topData['field_' + t] === 'red'
							})
							if (!allRed) {
								msg.timeUnit.forEach((t, index) => {
									if (topData['field_' + t] === 'red') {
										// msg.timeUnit.splice(index, 1)
										redUnit.push(t)
									}
								})
							}
							redUnit.forEach(red => {
								const index = msg.timeUnit.findIndex(item => {
									return item === red
								})
								msg.timeUnit.splice(index, 1)
							})
						})
						if (redUnit.length > 0) {
							topData.msg.push({
								timeUnit: redUnit
							})
						}
					})
				}
				this.tableData = res.topDataList || []
				// res.topDataList.forEach((p, index) => {
				// 	this.tableData.push({
				// 		id: index,
				// 		...p
				// 	})
				// })
				// 产品维度 前两列 工位 原材料
				if (this.$refs.filterBar.autoQueryType === 1) {
					this.tableColumn.push({
						prop: 'stationName', label: '工位', required: true
					})
					this.tableColumn.push({
						prop: 'materialName', label: '原材料', required: true
					})
					// 多级表头
					this.mergetableColumn.push({
						prop: '1',
						label: '工位',
						required: true
					}, {
						prop: '2',
						label: '原材料',
						required: true
					})
				}
				// 排程维度 前两列 工序 工位
				if (this.$refs.filterBar.autoQueryType === 2) {
					this.tableColumn.push({
						prop: 'stationName', label: '工位', required: true
					})
					this.tableColumn.push({
						prop: 'procedureName', label: '工序', required: true
					})
					// 多级表头
					this.mergetableColumn.push({
						prop: '1',
						label: '工位',
						required: true
					}, {
						prop: '2',
						label: '工序',
						required: true
					})
				}
				for (var i = 0; i < 24; i++) {
					this.tableColumn.push({
						prop: 'field_' + i, label: i.toString(), required: true, width: 60, fxRender: this.fieldRender, showOverflowTooltip: true
					})
				}
				this.tableShow = true
				if (this.headProduceList) {
					this.headProduceList.forEach((p, index) => {
						if (p !== 'red') {
							this.mergetableColumn.push({
								prop: p,
								label: p,
								required: true,
								align: 'center',
								childTableColumn: []
							})
						}
					})
					this.headProduceList.forEach((p, index) => {
						if (p !== 'red') {
							const pIndex = 3 * (index + 1)
							this.mergetableColumn[index + 2].childTableColumn.push({
								prop: pIndex + '',
								label: '开始',
								required: true
							}, {
								prop: pIndex + 1 + '',
								label: '结束',
								required: true
							}, {
								prop: pIndex + 2 + '',
								label: '数量',
								required: true
							})
						}
					})
				}
				this.mergeTableData = res.dataList || []
				this.mergetableShow = true
				return Promise.resolve(res.data)
			})
		},
		getProgram (planId) {
			return this.$fxApi('schedule.findDetailByParam')({
				query: {
					id: planId
				}
			}).then(res => {
				return Promise.resolve(res)
			})
		},
		getProgramDetails (planId) {
			return this.$fxApi('schedule.findProductionPlanDetail')({
				query: {
					productionPlanId: planId
				}
			}).then(res => {
				return Promise.resolve(res)
			})
		},
		fieldRender (h, { row, column }) {
			const property = column.property
			const filedVal = row[property]
			if (this.headProduceList) {
				const index = this.headProduceList.findIndex(item => {
					return item === filedVal && filedVal !== 'red'
				})
				const filedColor = index === -1 ? 'red' : this.produceColor[index]
				if (row.msg) {
					const filterMsg = row.msg.filter(msg => {
						return msg.timeUnit[0] + '' === property.split('_')[1]
					})
					if (filedVal && filterMsg.length > 0) {
						let msg = ''
						const filterVal = filterMsg[0].dateStr && filterMsg[0].dateStr.substring(filterMsg[0].dateStr.lastIndexOf('.'))
						if (filterVal === '.0000') {
							msg = filterMsg[0].dateStr.substring(0, filterMsg[0].dateStr.lastIndexOf('.'))
						} else {
							msg = filterMsg[0].dateStr || ''
						}
						return <el-tag
							color={filedColor}
							effect="dark"
							style="border: none;margin-left: 10px;width: auto;display: flex;line-height：28px;"
						>{filedVal === 'red' ? '' : msg}</el-tag>
					}
				}
			}
		},
		// 导出pdf
		downloadSprintTestReport () {
			this.getPdfFromHtml(this.$refs.sprintReport, '生产排程')
		},
		exportExcel () {
			axios({
				method: 'post',
				url: 'schedule/stationTask/export/exportExcelStationProcedure',
				data: this.getSearchParams(),
				responseType: 'blob'
			}).then((res) => {
				const blob = new Blob([res.data]) // Blob 对象表示一个不可变、原始数据的类文件对象
				const fileReader = new FileReader() // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
				fileReader.readAsDataURL(blob)
				// 开始读取指定的Blob中的内容。一旦完成，result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容
				fileReader.onload = (e) => {
					const a = document.createElement('a')
					const weidu = this.getSearchParams().autoQueryType === 1 ? '产品维度' : '排程维度'
					const fileName = '工序排程表' + weidu + this.$fxUtils.setDate(new Date())
					a.download = fileName + '.xlsx'
					a.style.display = 'none'
					a.href = URL.createObjectURL(blob)
					document.body.appendChild(a)
					a.click()
					document.body.removeChild(a)
				}
			}).catch(err => {
				console.log(err)
			})
			// this.$fxApi('schedule.exportExcelStationProcedure')({ data: this.getSearchParams(), responseType: 'blod' }).then(res => {
			// 	debugger
			// })
		},
		// 改变车间 给产线赋值
		changeCarRoom (carRoom) {
			const filterProductionLine = this.productionLineListCache.filter(p => {
				if (carRoom) {
					return p.carRoomId === carRoom
				} else {
					return p
				}
			})
			this.productionLineList = filterProductionLine
			const produtionLine = this.getSearchParams().productionLineIds
			this.findProcedureListByProcedureLineId(carRoom, produtionLine)
		},
		// 改变产线 给工序赋值
		changeProdutionLine (produtionLine) {
			const carRoomId = this.getSearchParams().carRoomId
			this.findProcedureListByProcedureLineId(carRoomId, produtionLine)
		},
		// 重置查询条件
		ResetSearch () {
			this.productionLineList = this.productionLineListCache
			this.findProcedureListByProcedureLineId()
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.organ-manage-container {
	flex: 1;
	display:flex
	flex-direction: column
	overflow: auto
	.tools-left, .tools-right {
		display:flex
		flex-direction: row
		align-items: center
	}
	.tools-left {
		flex: 1
	}
}
.productionScheduling-main {
	background-image: url('~images/img/productionScheduling-main.png');
	width: 128px;
	height: 128px;
	position: absolute;
	top: 45%;
	left: 50%;
}
.productionScheduling-main .pm-word{
	position: relative;
    width: 400px;
    left: -40px;
    bottom: -120px;
}
.productionScheduling-main a{
	text-decoration: underline;
    color: #409EFF;
}
</style>
